import React, { useEffect, useRef, useState } from 'react';
import { useParams } from '@umijs/max';
import { useModel } from '@umijs/max';
import { getResultByUser } from '@/services/swagger/resultController';
import * as echarts from 'echarts';
import { message, Spin, Card, Descriptions, Typography, Alert, Row, Col } from 'antd';
import { CheckCircleOutlined, ExclamationCircleOutlined, InfoCircleOutlined } from '@ant-design/icons';

const InterviewResult: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const { initialState } = useModel('@@initialState');
  const [result, setResult] = useState<API.Result | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const currentUser = initialState?.currentUser;
  const chartRef = useRef<HTMLDivElement>(null);
  const chartInstanceRef = useRef<echarts.ECharts | null>(null);

  /**
   * 获取面试结果
   */
  const getResult = async () => {
    if (!currentUser?.id || !id) {
      setError('缺少用户或面试ID');
      setLoading(false);
      return;
    }

    try {
      setLoading(true);
      const res = await getResultByUser({
        userId: currentUser.id,
        interviewId: id,
      });

      if (res.code === 0 && res.data) {
        message.success('获取面试结果成功');
        setResult(res.data);
      } else if (res.data === null) {
        setError('面试信息不存在');
      } else {
        setError(res.message || '获取面试结果失败');
        message.error(res.message || '获取失败');
      }
    } catch (err) {
      setError('网络请求失败，请重试');
      message.error('网络请求失败');
    } finally {
      setLoading(false);
    }
  };

  /**
   * 初始化 ECharts
   */
  const initChart = (echartStr: string) => {
    if (!chartRef.current || !echartStr) return;

    let option: echarts.EChartsOption;
    try {
      option = JSON.parse(echartStr);
    } catch (err) {
      console.error('ECharts 配置解析失败:', echartStr);
      message.error('图表配置格式错误');
      return;
    }

    // 如果已有实例，先销毁
    if (chartInstanceRef.current) {
      chartInstanceRef.current.dispose();
    }

    const chartInstance = echarts.init(chartRef.current);
    chartInstance.setOption(option);
    chartInstanceRef.current = chartInstance;

    // 处理窗口大小变化
    const resizeHandler = () => {
      chartInstance.resize();
    };
    window.addEventListener('resize', resizeHandler);

    // 返回清理函数
    return () => {
      window.removeEventListener('resize', resizeHandler);
      if (chartInstanceRef.current) {
        chartInstanceRef.current.dispose();
        chartInstanceRef.current = null;
      }
    };
  };

  useEffect(() => {
    getResult();
  }, [id, currentUser?.id]);

  // 初始化图表
  useEffect(() => {
    if (result && result.echarts) {
      return initChart(result.echarts);
    }
  }, [result?.echarts]);

  // 清理图表
  useEffect(() => {
    return () => {
      if (chartInstanceRef.current) {
        chartInstanceRef.current.dispose();
        chartInstanceRef.current = null;
      }
    };
  }, []);

  // 处理结果数据
  const renderResult = () => {
    if (!result) return null;

    // 根据得分判断评级
    const getGradeLevel = (score: number) => {
      if (score >= 90) return { level: '优秀', color: '#52c41a' };
      if (score >= 75) return { level: '良好', color: '#fa8c16' };
      if (score >= 60) return { level: '合格', color: '#faad14' };
      return { level: '待改进', color: '#f5222d' };
    };

    const gradeInfo = getGradeLevel(result.interviewGrade || 0);

    return (
      <div className="result-container">
        <Card
          title={
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <CheckCircleOutlined style={{ color: gradeInfo.color, fontSize: '20px' }} />
              <span>面试结果 - {result.interviewTitle || '面试分析'}</span>
            </div>
          }
          bordered={false}
          style={{
            marginBottom: 24,
            boxShadow: '0 4px 12px rgba(0,0,0,0.08)',
            borderRadius: 12
          }}
        >
          <Row gutter={24}>
            <Col xs={24} sm={12} md={8}>
              <div style={{ padding: 16, borderRight: '1px solid #f0f0f0' }}>
                <Typography.Text type="secondary" style={{ display: 'block', marginBottom: 8 }}>
                  面试时长
                </Typography.Text>
                <Typography.Title level={3} style={{ color: '#1890ff' }}>
                  {result.interviewDuration} 分钟
                </Typography.Title>
              </div>
            </Col>
            <Col xs={24} sm={12} md={8}>
              <div style={{ padding: 16, borderRight: '1px solid #f0f0f0' }}>
                <Typography.Text type="secondary" style={{ display: 'block', marginBottom: 8 }}>
                  面试得分
                </Typography.Text>
                <Typography.Title level={3} style={{ color: gradeInfo.color }}>
                  {result.interviewGrade} 分
                  <span style={{ marginLeft: 8, fontSize: '14px', color: '#8c8c8c' }}>
                    ({gradeInfo.level})
                  </span>
                </Typography.Title>
              </div>
            </Col>
            <Col xs={24} sm={12} md={8}>
              <div style={{ padding: 16 }}>
                <Typography.Text type="secondary" style={{ display: 'block', marginBottom: 8 }}>
                  问题数量
                </Typography.Text>
                <Typography.Title level={3} style={{ color: '#722ed1' }}>
                  {result.questionNum} 个
                </Typography.Title>
              </div>
            </Col>
          </Row>
        </Card>

        <Card
          title="面试官建议"
          bordered={false}
          style={{
            marginBottom: 24,
            boxShadow: '0 4px 12px rgba(0,0,0,0.08)',
            borderRadius: 12
          }}
        >
          <Typography.Paragraph
            style={{
              fontSize: '16px',
              lineHeight: 1.6,
              color: '#333',
              padding: '16px',
              backgroundColor: '#fafafa',
              borderRadius: 8
            }}
          >
            {result.suggestion || '暂无具体建议'}
          </Typography.Paragraph>
        </Card>

        <Card
          title="面试评价"
          bordered={false}
          style={{
            marginBottom: 24,
            boxShadow: '0 4px 12px rgba(0,0,0,0.08)',
            borderRadius: 12
          }}
        >
          <Typography.Paragraph
            style={{
              fontSize: '15px',
              lineHeight: 1.6,
              color: '#444',
              padding: '16px',
              backgroundColor: '#f9f9f9',
              borderRadius: 8
            }}
          >
            {result.comment || '暂无详细评价'}
          </Typography.Paragraph>
        </Card>

        <Card
          title="能力分析雷达图"
          bordered={false}
          style={{
            boxShadow: '0 4px 12px rgba(0,0,0,0.08)',
            borderRadius: 12
          }}
        >
          <div
            ref={chartRef}
            style={{
              width: '100%',
              height: '400px',
              backgroundColor: '#fff',
              borderRadius: 8,
              boxShadow: '0 2px 8px rgba(0,0,0,0.05)'
            }}
          />
        </Card>
      </div>
    );
  };

  return (
    <div className="interview-result-page" style={{ padding: '24px', maxWidth: '1200px', margin: '0 auto' }}>
      <div style={{
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-between',
        marginBottom: 24
      }}>
        <Typography.Title level={2} style={{ margin: 0, color: '#1890ff' }}>
          面试结果分析
        </Typography.Title>
        <div>
          <Typography.Text type="secondary" style={{ marginRight: 8 }}>
            面试 ID: {id}
          </Typography.Text>
          <Typography.Text type="secondary">
            申请人: {currentUser?.userAccount || '未知'}
          </Typography.Text>
        </div>
      </div>

      {error && (
        <Alert
          message="加载失败"
          description={error}
          type="error"
          showIcon
          style={{ marginBottom: 24 }}
          icon={<ExclamationCircleOutlined />}
        />
      )}

      {loading ? (
        <Spin
          size="large"
          style={{
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            height: '400px'
          }}
        />
      ) : (
        renderResult()
      )}

      {!loading && !error && !result && (
        <Alert
          message="未找到面试结果"
          description="您尚未参加该面试或面试结果尚未生成"
          type="info"
          showIcon
          style={{ marginBottom: 24 }}
          icon={<InfoCircleOutlined />}
        />
      )}
    </div>
  );
};

export default InterviewResult;
